package com._21cn.cms.template.web.controller;

import com._21cn.cms.common.FormSelector;
import com._21cn.cms.site.entity.Site;
import com._21cn.cms.site.service.SiteService;
import com._21cn.cms.template.entity.Template;
import com._21cn.cms.template.service.TemplateService;

import com._21cn.framework.http.HttpRequestInfo;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.base.controller.BaseController;
import com._21cn.framework.utils.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/admin/template/template")
public class TemplateController extends BaseController{

	private static String listView = "/admin/template/template/list";
    private static String showView = "/admin/template/template/show";
    private static String jsonView = "/admin/template/template/json";
    private static String formView = "/admin/template/template/form";
    private static String redirectListView = "redirect:/admin/template/template/list.do";

    private Map<String, String> propertyTitleMap = null;

    @Autowired
    private TemplateService templateService;

    @Autowired
    private SiteService siteService;
	
	@Autowired(required = false)
    @Qualifier("templateValidator")
    private Validator templateValidator;

    @RequestMapping("/list")
    public String listTemplate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", listView);
        setRequestModelMap( request, model, true );
        model.addAttribute("templateStatusMap", FormSelector.getTemplateStatusMap());
        model.addAttribute("templateTypeMap", FormSelector.getTemplateTypeMap());
        return view;
    }

    @RequestMapping("/search")
    public String searchTemplate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", jsonView );
        setRequestModelMap( request, model, true );
        PageList<Template> result = getPageList( model );
        for(Template template: result){
            if( template.getSiteId()>0 ){
                Site site = siteService.getById(template.getSiteId());
                template.setSiteName(site.getName());
            }
        }
        model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat) );
        return view;
    }

    @RequestMapping("/show")
    public String showTemplate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", showView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            Template template = templateService.getById( id );
            if( template == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
//            model.addAttribute( "statusMap", FormSelector.getStatusMap());
            model.addAttribute( "template", template );
        }
        setRequestModelMap(request, model);
        return view;
    }
	
	@RequestMapping("/edit")
    public String editTemplate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", formView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        Template template = new Template();
        if( id > 0 ){
            template = templateService.getById(id);
            if( template == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
        }
        String content = template.getContent();
        if(!StringUtil.isEmpty(content)){
            content = content.replace("</textarea>","&lt;/textarea&gt;");
            template.setContent(content);
        }
        model.addAttribute( "template", template );
        setRequestModelMap(request, model);
        return view;
    }
	
	@RequestMapping("/save")
    public String saveTemplate(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id>0 ){                                         //更新
            Template template = templateService.getById( id );
            if( bind( request, template, model,  templateValidator).hasErrors() ){
                return formView;
            }
            templateService.update( template );
        }else{                                              //添加
            Template template = new Template();
            if( bind( request, template, model,  templateValidator).hasErrors() ){
                return formView;
            }
            templateService.insert( template );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }
	
	@RequestMapping("/updateStatus")
    public String updateTemplateStatus(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = reqInfo.getIntParameter( "status", -1 );
        if( status < 0 ){
            model.clear();
            return redirectListView+ "?" + reqInfo.getParameter( "queryParam", "" );
        }
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            templateService.update( model );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    @RequestMapping("/delete")
    public String deleteTemplate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            templateService.delete( model );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    @RequestMapping({"/select"})
    public String selectTemplate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter("view", jsonView);
        setRequestModelMap(request, model, true);
        PageList<Template> result = getPageList(model);
        for (Template template : result) {
            template.setContent("");
            if (template.getSiteId().intValue() > 0) {
                Site site = (Site)this.siteService.getById(template.getSiteId());
                template.setSiteName(site.getName());
            }
        }
        model.addAttribute("objListJson", JSON.toJSONString(result));
        return view;
    }
	
	private PageList<Template> getPageList(ModelMap model) {
        if(model.containsKey("likeName"))
            model.put("likeName",model.get("likeName").toString().toLowerCase());
        PageList<Template> templateList = templateService.getList( model, Integer.parseInt(model.get("pageNo").toString()), Integer.parseInt(model.get("pageSize").toString()) );
        model.addAttribute( "templateList", templateList);
        model.addAttribute( "objList", templateList);
        model.addAttribute( "pageTurn", templateList.getPageTurn());
        model.addAttribute( "titleMap", getPropertyTitleMap() );
        return templateList;
    }

    private Map<String, String> getPropertyTitleMap() {
        if( propertyTitleMap == null ){
			propertyTitleMap = new HashMap<String,String>();
			propertyTitleMap.put( "id", "id" );
			propertyTitleMap.put( "siteId", "siteId" );
			propertyTitleMap.put( "name", "name" );
			propertyTitleMap.put( "templateType", "templateType" );
			propertyTitleMap.put( "filePath", "filePath" );
			propertyTitleMap.put( "content", "content" );
			propertyTitleMap.put( "status", "status" );
			propertyTitleMap.put( "memo", "memo" );
			propertyTitleMap.put( "createTime", "createTime" );
			propertyTitleMap.put( "createUserId", "createUserId" );
			propertyTitleMap.put( "modifyTime", "modifyTime" );
			propertyTitleMap.put( "modifyUserId", "modifyUserId" );
        }
        return propertyTitleMap;
    }
}
